console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { getinputData } from './data/cwbbData.js';

let baseInfoCache;
window.onload = function () {
  // 登录填写账号密码
  window.postMessage({
    event: 'getBaseInfo'
  }, '*');
};

window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    console.log(data);
    newfillInput(data.data);
    // fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }

  if (data.event === 'getBaseInfo') {
    baseInfoCache = data.data;
    if (window.location.href.includes('etax.guangxi.chinatax.gov.cn:9723/web/dzswj/ythclient/mh.html')) {
      autoInputAccount(baseInfoCache);
    }
  }
}, false);


/**
 * 调用接口获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    outPutType: 'xml', // 填报方式,
    isZip: true,
    filesNum: 3
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  let colseBtn = $('.layui-layer.layui-layer-page .layui-layer-setwin .layui-layer-close.layui-layer-close1');
  if (colseBtn.length) {
    colseBtn.click();
  }
  document.querySelector('#id_mh_login_img').click();
  setTimeout(() => {
    document.querySelector('#wdl_sfzdl_nav').click();
    setTimeout(() => {
      console.log(companyInfo);
      // $('input[name="USER_ZH3"]').val(companyInfo.nationalTaxId);
      let nsrsbh = document.querySelector('#wep_form_sfzdl');
      let divs = document.createElement('div');
      let div1 = document.createElement('div');
      let div2 = document.createElement('div');
      divs.innerText = `纳税人识别号：${companyInfo.nationalTaxId}`;
      div1.innerText = `纳税人识别号：${companyInfo.nationalTaxPass}`;
      div2.innerText = `法人身份证： ${companyInfo.idcard}`;
      nsrsbh.append(divs);
      nsrsbh.append(div1);
      nsrsbh.append(div2);
    }, 500);
  }, 500);
  // $('.username').val(companyInfo.nationalTaxAccount || companyInfo.nationalTaxId);
  // $('#topPw').val(companyInfo.nationalTaxPass);
}

function newfillInput ({ saasData }) {
  console.log(saasData);
  let sheet = saasData.sheet;
  let isYearReport = saasData.isYearReport;
  let ins = saasData.data.openParams.taxInfo.institution === '2013' ? 'xqykjzz' : 'qykjzz';
  let inputData;
  if (isYearReport && ins === 'xqykjzz') {
    inputData = saasData.data.openParams.inputData.data[sheet];
    let lastYearData = saasData.data.openParams.inputData.lastYearData[sheet];
    if (sheet === 'profit' || sheet === 'cash') {
      inputData = inputData.map((item, index) => {
        let obj = {};
        obj.colValue1 = item.colValue1;
        obj.colValue2 = lastYearData[index].colValue1;
        obj.reportItemName = lastYearData[index].reportItemName;
        return obj;
      });
    }
  } else {
    inputData = saasData.data.openParams.inputData.data[sheet];
  }
  if (['balance', 'profit', 'cash'].includes(sheet)) {
    try {
      let data = getinputData(inputData, ins, sheet, isYearReport);
      let contentIframe = document.querySelector('#ym-window iframe').contentDocument;
      let divs = contentIframe.querySelectorAll('body > div > table > tbody > tr > td > div > div');
      let currentDivs = Array.from(divs).find(item => item.id.includes('table') && item.style.display !== 'none');
      let iframe = currentDivs.querySelector('iframe') ? currentDivs.querySelector('iframe').contentDocument : contentIframe;
      console.log(iframe);
      data.forEach(({ key, value = 0 }) => {
        let input = iframe.querySelector(`#${key}`);
        input.set('value', value || 0)
          .set('realvalue', value || 0)
          .fireEvent('change');
      });
      window.postMessage(
        {
          event: 'fillInputDone',
          data: {
            message: '填报成功'
          }
        },
        '*'
      );
    } catch (e) {
      window.postMessage(
        {
          event: 'fillInputDone',
          data: {
            message: '填报失败'
          }
        },
        '*'
      );
    }
  }
}

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { taxInfo, popupParams }) {
  blob = new Blob([blob], { type: 'application/zip' });
  let a = document.createElement('a');
  // 指定生成的文件名
  // let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'}`;
  let name = '资产负债表';
  let { type } = popupParams;
  type === 'cash' && (name = '现金流量表');
  type === 'profit' && (name = '利润表');
  const start = taxInfo.skssqq.replace(/-/g, '');
  const end = taxInfo.skssqz.replace(/-/g, '');
  a.download = `${name}_${start}_${end}.zip`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}
